Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
path-to-regexp
Advanced tools
The path-to-regexp package is a utility for converting paths to and from regular expressions. It is commonly used for routing in web applications, allowing developers to define patterns for URL paths and extract parameters from them.
Path to RegExp Conversion
Convert a path string into a regular expression. It can also extract named parameter keys.
const { pathToRegexp } = require('path-to-regexp');
const keys = [];
const regexp = pathToRegexp('/user/:id', keys);
Extracting Parameters from a Path
Match a path against a pattern and extract the named parameters.
const { match } = require('path-to-regexp');
const matchFn = match('/user/:id');
const result = matchFn('/user/123');
// result.params will contain the extracted parameters
Compile Path to String
Compile a path function from a string pattern, which can then be used to construct paths with parameters.
const { compile } = require('path-to-regexp');
const toPath = compile('/user/:id');
const path = toPath({ id: 123 });
// path will be '/user/123'
Express is a web application framework for Node.js that includes its own routing capabilities, which are similar to path-to-regexp. Express uses path-to-regexp internally for its routing logic.
React Router is a routing library for React that uses path-to-regexp-like pattern matching for defining routes and extracting parameters, but it is specifically tailored for React applications.
url-pattern is another library for matching URLs against patterns and extracting parameters. It offers a similar API to path-to-regexp but with different syntax and additional options for pattern matching.
Turn a path string such as
/user/:name
into a regular expression.
npm install path-to-regexp --save
const {
match,
pathToRegexp,
compile,
parse,
stringify,
} = require("path-to-regexp");
Parameters match arbitrary strings in a path by matching up to the end of the segment, or up to any proceeding tokens. They are defined by prefixing a colon to the parameter name (:foo
). Parameter names can use any valid JavaScript identifier, or be double quoted to use other characters (:"param-name"
).
const fn = match("/:foo/:bar");
fn("/test/route");
//=> { path: '/test/route', params: { foo: 'test', bar: 'route' } }
Wildcard parameters match one or more characters across multiple segments. They are defined the same way as regular parameters, but are prefixed with an asterisk (*foo
).
const fn = match("/*splat");
fn("/bar/baz");
//=> { path: '/bar/baz', params: { splat: [ 'bar', 'baz' ] } }
Braces can be used to define parts of the path that are optional.
const fn = match("/users{/:id}/delete");
fn("/users/delete");
//=> { path: '/users/delete', params: {} }
fn("/users/123/delete");
//=> { path: '/users/123/delete', params: { id: '123' } }
The match
function returns a function for matching strings against a path:
false
to disable all processing. (default: decodeURIComponent
)const fn = match("/foo/:bar");
Please note: path-to-regexp
is intended for ordered data (e.g. paths, hosts). It can not handle arbitrarily ordered data (e.g. query strings, URL fragments, JSON, etc).
The pathToRegexp
function returns a regular expression for matching strings against paths. It
false
)true
)[^/]
for :named
parameters. (default: '/'
)true
)const { regexp, keys } = pathToRegexp("/foo/:bar");
The compile
function will return a function for transforming parameters into a valid path:
[^/]
for :named
parameters. (default: '/'
)false
to disable entirely. (default: encodeURIComponent
)const toPath = compile("/user/:id");
toPath({ id: "name" }); //=> "/user/name"
toPath({ id: "café" }); //=> "/user/caf%C3%A9"
const toPathRepeated = compile("/*segment");
toPathRepeated({ segment: ["foo"] }); //=> "/foo"
toPathRepeated({ segment: ["a", "b", "c"] }); //=> "/a/b/c"
// When disabling `encode`, you need to make sure inputs are encoded correctly. No arrays are accepted.
const toPathRaw = compile("/user/:id", { encode: false });
toPathRaw({ id: "%3A%2F" }); //=> "/user/%3A%2F"
Transform TokenData
(a sequence of tokens) back into a Path-to-RegExp string.
TokenData
instanceconst data = new TokenData([
{ type: "text", value: "/" },
{ type: "param", name: "foo" },
]);
const path = stringify(data); //=> "/:foo"
encode: false
and decode: false
to keep raw paths passed around.encodePath
.The parse
function accepts a string and returns TokenData
, the set of tokens and other metadata parsed from the input string. TokenData
is can used with match
and compile
.
x => x
, recommended: encodeurl
)TokenData
is a sequence of tokens, currently of types text
, parameter
, wildcard
, or group
.
In some applications, you may not be able to use the path-to-regexp
syntax, but still want to use this library for match
and compile
. For example:
import { TokenData, match } from "path-to-regexp";
const tokens = [
{ type: "text", value: "/" },
{ type: "parameter", name: "foo" },
];
const path = new TokenData(tokens);
const fn = match(path);
fn("/test"); //=> { path: '/test', index: 0, params: { foo: 'test' } }
An effort has been made to ensure ambiguous paths from previous releases throw an error. This means you might be seeing an error when things worked before.
?
or +
In past releases, ?
, *
, and +
were used to denote optional or repeating parameters. As an alternative, try these:
?
), use an empty segment in a group such as /:file{.:ext}
.+
), only wildcard matching is supported, such as /*path
.*
), use a group and a wildcard parameter such as /files{/*path}
.(
, )
, [
, ]
, etc.Previous versions of Path-to-RegExp used these for RegExp features. This version no longer supports them so they've been reserved to avoid ambiguity. To use these characters literally, escape them with a backslash, e.g. "\\("
.
Parameter names must be provided after :
or *
, and they must be a valid JavaScript identifier. If you want an parameter name that isn't a JavaScript identifier, such as starting with a number, you can wrap the name in quotes like :"my-name"
.
Parameter names can be wrapped in double quote characters, and this error means you forgot to close the quote character.
Path-To-RegExp breaks compatibility with Express <= 4.x
in the following ways:
*
must have a name, matching the behavior of parameters :
.?
is no longer supported, use braces instead: /:file{.:ext}
.()[]?+!
).:"this"
.MIT
FAQs
Express style path to RegExp utility
The npm package path-to-regexp receives a total of 0 weekly downloads. As such, path-to-regexp popularity was classified as not popular.
We found that path-to-regexp demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.